package com.easytouch.core.utils;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.easytouch.core.Configure;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;


public class GoodsDataBase {

	private static SQLiteDatabase db ;

	private static GoodsDataBase instance = new GoodsDataBase();

	private Log mLogger;

	private GoodsDataBase(){
		mLogger = new Log("db.txt");
		if(db == null && SDCardTools.isSDCardIsReady() && Configure.path != null) {
			try {
				db = SQLiteDatabase.openOrCreateDatabase(Configure.path + "/db/goods.db", null);
			}catch(Exception e)
			{
				db = null;
				mLogger.e("db open failed:" + e.toString());
				copyAssertDBFile2File();
			}
		}
	}

	public static GoodsDataBase getInstance() {
		return instance;
	}

//	public GoodsModel queryGoodsById(String goodsId) {
//		if ("".equals(goodsId))
//			return null;
//
//		if (Configure.goodsList == null)
//			return null;
//		GoodsModel item = null;
//		for (int i = 0; i < Configure.goodsList.size(); i++) {
//			item = Configure.goodsList.get(i);
//			if (goodsId.equals(item.getCode())) {
//				return item;
//			}
//		}
//		return null;
//	}
//
//	public List<GoodsModel> queryGoodsByIds(String query_type,
//			ArrayList<String> goodsIds) {
//		if ("".equals(query_type) || goodsIds == null) {
//			return null;
//		}
//
//		if (Configure.goodsList == null) {
//			return null;
//		}
//		List<GoodsModel> mList = new ArrayList<GoodsModel>();
//		GoodsModel goods = null;
//		for (int i = 0; i < Configure.goodsList.size(); i++) {
//			goods = Configure.goodsList.get(i);
//			if (query_type.equals(goods.getType()) && goodsIds.contains(goods.getCode())) {
//				mList.add(goods);
//			}
//		}
//		return mList;
//	}
//
//	public GoodsModel queryGoods(String query_type,String goodsId){
//		if ("".equals(query_type) || "".equals(goodsId)) {
//			return null;
//		}
//
//		if (Configure.goodsList == null) {
//			return null;
//		}
//		GoodsModel goods = null;
//		for (int i = 0; i < Configure.goodsList.size(); i++) {
//			goods = Configure.goodsList.get(i);
//			if (query_type.equals(goods.getType()) && goodsId.equals(goods.getCode())) {
//				return goods;
//			}
//		}
//		return null;
//	}
//
//	public List<GoodsModel> find(String query_type){
//		if ("".equals(query_type))
//			return null;
//
//		if (Configure.goodsList == null) {
//			return null;
//		}
//		List<GoodsModel> mList = new ArrayList<GoodsModel>();
//		GoodsModel item = null;
//		for (int i = 0; i < Configure.goodsList.size(); i++) {
//			item = Configure.goodsList.get(i);
//			if (query_type.equals(item.getType())) {
//				mList.add(item);
//			}
//		}
//		return mList;
//	}

	public synchronized boolean insertMessage(String type, String message, String remark) {
		String sql = "insert into monitor (type, content, remark) values('" + type + "','" + message +"','" + remark + "')";
		//logger.i("insert message :"+sql);
		if(db == null)
		{
			return false;
		}
		try {
			db.execSQL(sql);
			return true;
		} catch (SQLException e) {
			mLogger.e("db insert failed:" + e.toString());
			return false;
		}catch (IllegalStateException e){
			mLogger.e("db insert failed1:" + e.toString());
			return false;
		}
	}

	public synchronized String[] getMessage() {
		if(db == null)
		{
			return null;
		}
		Cursor cursor = null;
		try {
			cursor = db.rawQuery("select * from monitor",null);
			int count = cursor.getCount();
			if(count == 0) return null;
			String[] messages = new String[count];
			for(int i = 0; i < count; i++){
				if(!cursor.moveToNext()) break;
				messages[i] = cursor.getInt(cursor.getColumnIndex("_id")) + ";" + cursor.getString(cursor.getColumnIndex("content")) + ";" + cursor.getString(cursor.getColumnIndex("type"));
			}
			return messages;
		} catch (Exception e) {
			mLogger.e("db get message failed:" + e.toString());
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return null;
	}

	public synchronized boolean getLastMessageAndUpdate(String type, String message, String remark)
	{
		if(db == null)
		{
			return false;
		}
		Cursor cursor = null;
		try {
			cursor = db.rawQuery("select _id from monitor where type = \'" + type + "\' order by _id desc limit 0,1",null);
			int count = cursor.getCount();
			mLogger.i("count:" + count);
			if(count == 0)
			{
				return insertMessage(type, message, remark);
			}
//			String[] messages = new String[count];
//			for(int i = 0; i < count; i++){
//				if(!cursor.moveToNext()) break;
//				messages[i] = cursor.getInt(cursor.getColumnIndex("_id")) + ";" + cursor.getString(cursor.getColumnIndex("content")) + ";" + cursor.getString(cursor.getColumnIndex("type"));
//			}
			if(cursor.moveToNext())
			{
				int id = cursor.getInt(cursor.getColumnIndex("_id"));
				db.execSQL("update monitor set content = \'" + message + "\' where _id = " + String.valueOf(id));
			}
			return true;
		} catch (Exception e) {
			mLogger.e("db getLastMessageAndUpdate failed:" + e.toString());
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return false;
	}

	public synchronized void deleteMessage(String id) {
		if(db == null)
		{
			return;
		}
        try {
			db.delete("monitor", "_id=?", new String[] { id });
		} catch (Exception e) {
			mLogger.e("db delete failed:" + e.toString());
		}
    }

	public synchronized void deleteMessageExceptType(String type) {
		if(db == null)
		{
			return;
		}
		try {
			db.delete("monitor", "type != ?", new String[] { type });
		} catch (Exception e) {
			mLogger.e("db delete failed:" + e.toString());
		}
	}

	public synchronized boolean queryMessage(String type){
		if(db == null)
		{
			return false;
		}
		Cursor cursor = null;
		try {
			cursor = db.rawQuery("select * from monitor where type = ?",new String[]{type});
			if(cursor.moveToFirst()) return true;
		} catch (Exception e) {
			mLogger.e("db query message failed:" + e.toString());
		} finally {
			if (cursor != null)
				cursor.close();
		}
		return false;
	}

	/**
	 * 使用assert目录中的db文件来替换目录中的db
	 */
	public synchronized void copyAssertDBFile2File()
	{
		try{
			if(db != null)
			{
				db.close();
			}
			if(Configure.context != null && Configure.path != null)
			{
				File dir = new File(Configure.path + "/db");
				// 如果目录不中存在，创建这个目录
				if (!dir.exists())
					dir.mkdir();
				File file = new File(Configure.path + "/db/goods.db");
				try {
					if(file.exists())
					{
						file.delete();
					}
//				if (!file.exists()) {
					InputStream is = Configure.context.getResources().getAssets().open("goods.db");
					FileOutputStream fos = new FileOutputStream(file);
					byte[] buffer = new byte[7168];
					int count;
					while ((count = is.read(buffer)) > 0) {
						fos.write(buffer, 0, count);
					}
					fos.close();
					is.close();
//				}
				} catch (Exception e) {
					mLogger.e("db copy failed:" + e.toString());
					db = null;
					return;
				}

				if(SDCardTools.isSDCardIsReady()) {
					try {
						db = SQLiteDatabase.openOrCreateDatabase(Configure.path + "/db/goods.db", null);
					}catch(Exception e)
					{
						db = null;
						mLogger.e("db open failed:" + e.toString());
					}
				}
			}
			else
			{
				mLogger.e("db context or path is null");
			}
		}catch(IllegalStateException e){
			e.printStackTrace();
		}
	}
}
